package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 设置开关量逻辑状态
 * Created by zwz on 2020/4/22.
 */
public class Cmd_24Fragment extends BaseFragment {

    @BindView(R.id.sp_id)
    Spinner spId;
    @BindView(R.id.cb_enalbe)
    CheckBox cbEnalbe;
    @BindView(R.id.rbtn_positive)
    RadioButton rbtnPositive;
    @BindView(R.id.rbtn_negative)
    RadioButton rbtnNegative;
    @BindView(R.id.radio)
    RadioGroup radio;



    public static Cmd_24Fragment newInstance() {
        Bundle args = new Bundle();
        Cmd_24Fragment fragment = new Cmd_24Fragment();
        fragment.setArguments(args);


        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_24;
    }

    @Override
    protected void initView() {

        String[] ids = {"1", "2", "3", "4"};
        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_spinner_dropdown_item, ids);
        spId.setAdapter(mAdapter);
    }



    private  void set(){
        String id = String.format(Locale.CHINA, "%02d", Integer.parseInt(spId.getSelectedItem().toString()));
       // 00=正逻辑 01=负逻辑，
        //正逻辑则代表 00 正常,01 报警,
        // 负逻辑代表 01 正常,00 报警,
        String logic = rbtnPositive.isChecked() ? "00" : "01";
        //“0”表示禁止采集，“1”表示允许采集
        String enable = cbEnalbe.isChecked() ? "01" : "00";
        sendData(id+" "+logic+" "+enable);
    }

    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_24, data);

        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();

                String[] data = msg.split(" ");
                if (data.length < 18) {
                    ToastUtil.info(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_24)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        ToastUtil.success("设置成功");
                    } else {
                        ToastUtil.error("设置失败");
                    }

                }


            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }


    @OnClick(R.id.btn_set)
    public void onViewClicked() {
        set();
    }
}
